/**
 * Responsive Optimization Panel Component
 * 响应式优化面板组件 - 桌面端Tab，移动端抽屉
 */
import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Tabs,
  Button,
  Progress,
  List,
  Tag,
  Space,
  Tooltip,
  Modal,
  message,
  Spin,
  Badge,
  Row,
  Col,
  Statistic,
  Alert,
  Drawer,
  Typography,
  Checkbox,
  Divider,
  Empty
} from 'antd';
import {
  BulbOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  ThunderboltOutlined,
  EditOutlined,
  FileSearchOutlined,
  LinkOutlined,
  PictureOutlined,
  GlobalOutlined,
  ReloadOutlined,
  DownloadOutlined,
  EyeOutlined,
  RollbackOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { useBreakpoint } from '../../hooks/useBreakpoint';
import { Show, Hide } from '../Responsive/ResponsiveExports';
import { useOptimizationStore } from '../../stores/optimization.store';
import { optimizationService } from '../../services/optimization.service';
import './responsive-optimization-style.css';

const { Title, Paragraph, Text } = Typography;

interface ResponsiveOptimizationPanelProps {
  content: string;
  title?: string;
  articleId?: string;
  onOptimized?: (content: string) => void;
  visible?: boolean;
  onClose?: () => void;
}

interface SuggestionItem {
  id: string;
  type: string;
  priority: 'high' | 'medium' | 'low';
  description: string;
  detail: string;
  location?: string;
  original_text?: string;
  suggested_text?: string;
  impact_score: number;
  auto_applicable: boolean;
  applied: boolean;
}

const ResponsiveOptimizationPanel: React.FC<ResponsiveOptimizationPanelProps> = ({
  content,
  title,
  articleId,
  onOptimized,
  visible = true,
  onClose
}) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const {
    currentAnalysis,
    isAnalyzing,
    selectedSuggestions,
    appliedSuggestions,
    setCurrentAnalysis,
    setAnalyzing,
    toggleSuggestion,
    clearSelection,
    addAppliedSuggestion
  } = useOptimizationStore();

  const [activeTab, setActiveTab] = useState('overview');
  const [suggestions, setSuggestions] = useState<SuggestionItem[]>([]);
  const [isApplying, setIsApplying] = useState(false);
  const [previewDrawerVisible, setPreviewDrawerVisible] = useState(false);
  const [optimizedContent, setOptimizedContent] = useState('');
  const [compareModalVisible, setCompareModalVisible] = useState(false);
  const [filterPriority, setFilterPriority] = useState<string>('all');

  // 分析内容
  const analyzeContent = useCallback(async () => {
    if (!content || content.trim().length === 0) {
      message.warning('请先输入内容');
      return;
    }

    setAnalyzing(true);
    try {
      const result = await optimizationService.analyzeContent({
        content,
        title: title || '未命名文章',
        articleId
      });

      setCurrentAnalysis(result);
      setSuggestions(result.suggestions || []);
      message.success('分析完成');
    } catch (error) {
      console.error('Analysis failed:', error);
      message.error('分析失败，请重试');
    } finally {
      setAnalyzing(false);
    }
  }, [content, title, articleId, setAnalyzing, setCurrentAnalysis]);

  // 自动分析
  useEffect(() => {
    if (visible && content && content.length > 100) {
      analyzeContent();
    }
  }, [visible]); // eslint-disable-line react-hooks/exhaustive-deps

  // 应用优化建议
  const handleApplySuggestions = async () => {
    if (selectedSuggestions.length === 0) {
      message.warning('请先选择要应用的建议');
      return;
    }

    setIsApplying(true);
    try {
      const result = await optimizationService.applySuggestions({
        content,
        suggestionIds: selectedSuggestions
      });

      setOptimizedContent(result.optimizedContent);
      onOptimized?.(result.optimizedContent);

      // 标记为已应用
      selectedSuggestions.forEach(id => addAppliedSuggestion(id));
      clearSelection();

      message.success('优化建议已应用');

      if (isMobile && onClose) {
        onClose();
      }
    } catch (error) {
      console.error('Apply suggestions failed:', error);
      message.error('应用建议失败');
    } finally {
      setIsApplying(false);
    }
  };

  // 渲染概览Tab
  const renderOverview = () => {
    if (!currentAnalysis) {
      return (
        <Empty
          description="暂无分析结果"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={analyzeContent}
            loading={isAnalyzing}
            className={isMobile ? 'h-touch' : ''}
          >
            开始分析
          </Button>
        </Empty>
      );
    }

    return (
      <div className={isMobile ? 'mobile-overview' : 'overview'}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8}>
            <Card size={isMobile ? 'small' : 'default'}>
              <Statistic
                title="质量评分"
                value={currentAnalysis.qualityScore || 0}
                suffix="/ 100"
                valueStyle={{ color: '#3f8600', fontSize: isMobile ? '24px' : '32px' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card size={isMobile ? 'small' : 'default'}>
              <Statistic
                title="优化建议"
                value={suggestions.length}
                suffix="条"
                valueStyle={{ fontSize: isMobile ? '24px' : '32px' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card size={isMobile ? 'small' : 'default'}>
              <Statistic
                title="已应用"
                value={appliedSuggestions.length}
                suffix="条"
                valueStyle={{ color: '#1890ff', fontSize: isMobile ? '24px' : '32px' }}
              />
            </Card>
          </Col>
        </Row>

        <Divider />

        <Space direction="vertical" style={{ width: '100%' }} size={isMobile ? 'small' : 'middle'}>
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={analyzeContent}
            loading={isAnalyzing}
            block={isMobile}
            className={isMobile ? 'h-touch' : ''}
          >
            重新分析
          </Button>
        </Space>
      </div>
    );
  };

  // 渲染建议列表
  const renderSuggestions = () => {
    const filteredSuggestions = filterPriority === 'all'
      ? suggestions
      : suggestions.filter(s => s.priority === filterPriority);

    return (
      <div className={isMobile ? 'mobile-suggestions' : 'suggestions'}>
        <Space
          direction={isMobile ? 'vertical' : 'horizontal'}
          style={{ marginBottom: 16, width: isMobile ? '100%' : 'auto' }}
        >
          <Space.Compact>
            <Button
              type={filterPriority === 'all' ? 'primary' : 'default'}
              onClick={() => setFilterPriority('all')}
              size={isMobile ? 'middle' : 'small'}
            >
              全部
            </Button>
            <Button
              type={filterPriority === 'high' ? 'primary' : 'default'}
              onClick={() => setFilterPriority('high')}
              size={isMobile ? 'middle' : 'small'}
            >
              高优先级
            </Button>
            <Button
              type={filterPriority === 'medium' ? 'primary' : 'default'}
              onClick={() => setFilterPriority('medium')}
              size={isMobile ? 'middle' : 'small'}
            >
              中优先级
            </Button>
            <Button
              type={filterPriority === 'low' ? 'primary' : 'default'}
              onClick={() => setFilterPriority('low')}
              size={isMobile ? 'middle' : 'small'}
            >
              低优先级
            </Button>
          </Space.Compact>
        </Space>

        <List
          dataSource={filteredSuggestions}
          renderItem={(suggestion) => (
            <List.Item
              className={isMobile ? 'mobile-suggestion-item' : 'suggestion-item'}
              actions={
                isMobile
                  ? []
                  : [
                      <Checkbox
                        checked={selectedSuggestions.includes(suggestion.id)}
                        onChange={() => toggleSuggestion(suggestion.id)}
                        disabled={suggestion.applied}
                      >
                        选择
                      </Checkbox>
                    ]
              }
            >
              <List.Item.Meta
                avatar={
                  suggestion.priority === 'high' ? (
                    <WarningOutlined style={{ color: '#ff4d4f', fontSize: isMobile ? '20px' : '24px' }} />
                  ) : suggestion.priority === 'medium' ? (
                    <BulbOutlined style={{ color: '#faad14', fontSize: isMobile ? '20px' : '24px' }} />
                  ) : (
                    <CheckCircleOutlined style={{ color: '#52c41a', fontSize: isMobile ? '20px' : '24px' }} />
                  )
                }
                title={
                  <Space>
                    <Text strong style={{ fontSize: isMobile ? '15px' : '14px' }}>
                      {suggestion.description}
                    </Text>
                    {suggestion.applied && <Tag color="success">已应用</Tag>}
                  </Space>
                }
                description={
                  <div style={{ fontSize: isMobile ? '14px' : '13px' }}>
                    {suggestion.detail}
                    {suggestion.original_text && (
                      <div style={{ marginTop: 8 }}>
                        <Text type="secondary">原文：</Text>
                        <Text code>{suggestion.original_text}</Text>
                      </div>
                    )}
                    {suggestion.suggested_text && (
                      <div style={{ marginTop: 4 }}>
                        <Text type="secondary">建议：</Text>
                        <Text code type="success">{suggestion.suggested_text}</Text>
                      </div>
                    )}
                  </div>
                }
              />
              {isMobile && (
                <div style={{ marginTop: 8 }}>
                  <Checkbox
                    checked={selectedSuggestions.includes(suggestion.id)}
                    onChange={() => toggleSuggestion(suggestion.id)}
                    disabled={suggestion.applied}
                    className="h-touch"
                  >
                    选择此建议
                  </Checkbox>
                </div>
              )}
            </List.Item>
          )}
          locale={{ emptyText: '暂无优化建议' }}
        />

        {selectedSuggestions.length > 0 && (
          <div
            className={isMobile ? 'mobile-action-buttons' : 'action-buttons'}
            style={{ marginTop: 16 }}
          >
            <Space size={isMobile ? 'small' : 'middle'}>
              <Button
                type="primary"
                icon={<CheckCircleOutlined />}
                onClick={handleApplySuggestions}
                loading={isApplying}
                className={isMobile ? 'h-touch' : ''}
              >
                应用选中建议 ({selectedSuggestions.length})
              </Button>
              <Button
                onClick={clearSelection}
                className={isMobile ? 'h-touch' : ''}
              >
                清除选择
              </Button>
            </Space>
          </div>
        )}
      </div>
    );
  };

  // Tab 项
  const tabItems = [
    {
      key: 'overview',
      label: (
        <span className={isMobile ? 'text-mobile-sm' : ''}>
          <FileSearchOutlined /> 概览
        </span>
      ),
      children: renderOverview()
    },
    {
      key: 'suggestions',
      label: (
        <span className={isMobile ? 'text-mobile-sm' : ''}>
          <BulbOutlined /> 建议 {suggestions.length > 0 && `(${suggestions.length})`}
        </span>
      ),
      children: renderSuggestions()
    }
  ];

  // 桌面端内容
  const desktopContent = (
    <div className="optimization-panel">
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
      />
    </div>
  );

  // 移动端抽屉内容
  const mobileContent = (
    <Drawer
      title={
        <div className="mobile-drawer-header">
          <Space>
            <ThunderboltOutlined />
            <span className="text-mobile-base font-bold">内容优化</span>
          </Space>
        </div>
      }
      placement="bottom"
      height="85%"
      open={visible}
      onClose={onClose}
      className="optimization-mobile-drawer"
      closeIcon={<CloseOutlined className="h-touch w-touch" />}
    >
      <Spin spinning={isAnalyzing}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
          className="mobile-tabs"
        />
      </Spin>
    </Drawer>
  );

  return (
    <>
      <Hide breakpoint="mobile">
        <Spin spinning={isAnalyzing}>
          {desktopContent}
        </Spin>
      </Hide>

      <Show breakpoint="mobile">
        {mobileContent}
      </Show>
    </>
  );
};

export default ResponsiveOptimizationPanel;
